package com.polaris.live.widget

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import com.bumptech.glide.Glide
import com.polaris.live.common.util.JsonUtils
import com.polaris.live.databinding.WidgetUserFlagBinding
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CommonUtils.splitLabelUrl
import com.polaris.live.utils.image.ImageUtils

/**
 * 用户标签
 *
 * @author Created by 半仙 on 2024/9/28/028 15:33
 */
class UserFlagView(context: Context, attributeSet: AttributeSet) : LinearLayout(context, attributeSet) {

    private val mBinding = WidgetUserFlagBinding.inflate(LayoutInflater.from(context), this, true)

    private val mListView = mutableListOf<ImageView>()

    fun setLabel(json: String?) {
        if (json?.isNotEmpty() == true) {
            setLabel(JsonUtils.fromJson<List<String>>(json))
        } else {
            visibility = View.GONE
        }
    }

    fun setLabel(label: List<String>?) {
        if (label?.isNotEmpty() == true) {
            val labelSize = label.size
            visibility = View.VISIBLE
            //如果保存的view 大于或等于 展示数量
            if (mListView.size >= labelSize) {
                mListView.forEachIndexed { index, imageView ->
                    val item = label.getOrNull(index)
                    if (item?.isNotEmpty() == true) {
                        imageView.visibility = View.VISIBLE
                        Glide.with(context).load(ImageUtils.imgPath(splitLabelUrl(imageView, item))).into(imageView)
                    } else {
                        imageView.visibility = View.GONE
                    }
                }
            } else {
                val tempViews = mutableListOf<ImageView>()
                label.forEachIndexed { index, s ->
                    val oldImage = mListView.getOrNull(index)
                    if (oldImage == null) {
                        val newImage = ImageView(context).apply {
                            Glide.with(context).load(ImageUtils.imgPath(CommonUtils.splitLabelUrl(this, s))).into(this)
                        }
                        mBinding.widgetLlFlag.addView(newImage)
                        tempViews.add(newImage)
                    } else {
                        Glide.with(context).load(ImageUtils.imgPath(CommonUtils.splitLabelUrl(oldImage, s))).into(oldImage)
                    }
                }
                mListView.addAll(tempViews)
            }
        } else {
            visibility = View.GONE
        }
    }


}